#!/usr/bin/env python
# Modificacion del ejemplo http://matplotlib.org/examples/animation/animate_decay.html
#
# Requiere matplotlib

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

import sys

# CONFIG
XLIMITS = (0, 1)
YLIMITS = (0, 3.3)
CONTINUO = True
INTERVAL_UPDATE = 10
F_SAMPLE = 1000.0
STEP = 1.0/F_SAMPLE

def data_gen():
   StartTime = 0.0
   line = sys.stdin.readline()
   while line:
      try:
         n = int(line)
         StartTime += STEP
         yield StartTime, n * 3.3 / 1024
      except:
         pass
      line = sys.stdin.readline()

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], lw=2)
ax.set_ylim(*YLIMITS)

XDELTA = XLIMITS[1] - XLIMITS[0]
ax.set_xlim(*XLIMITS)
ax.grid()
xdata, ydata = [], []

def run(data):
   # update the data (recieved from the frame_generator 'data_gen'
   t,y = data 
   xdata.append(t)
   ydata.append(y)
   xmin, xmax = ax.get_xlim()

   if t >= xmax:
      if not CONTINUO:
         del xdata[:-1] # delete all except the new one. 'start again'
         del ydata[:-1]
      else:
         del xdata[0]
         del ydata[0]
      ax.set_xlim(min(xdata), max(xdata))
      #ax.set_ylim(min(ydata), max(ydata))
   line.set_data(xdata, ydata)
   return line,

ani = animation.FuncAnimation(fig, run, frames=data_gen, blit=True, interval=INTERVAL_UPDATE, repeat=False)
plt.show()
